package Java8Test;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Predicate;

public class LambdaTest2 {
    public static String processFile(BufferedReaderProcessor p) throws IOException{
        BufferedReader br = new BufferedReader(new FileReader("C:/Users/n12/Desktop/zenghm/carNo1.txt"));
        return p.process(br);
    }

    public interface BufferedReaderProcessor {
        String process(BufferedReader b) throws IOException;
    }

    public static <T> List<T> filter(List<T> list, Predicate<T> p) {
        List<T> results = new ArrayList<>();
        for (T s : list) {
            if (p.test(s)) {
                results.add(s);
            }
        }
        return results;
    }

    public static <T> void forEach(List<T> list, Consumer<T> c) {
        for (T i : list) {
            c.accept(i);
        }
    }

    public static <T, R> List<R> map(List<T> list, Function<T, R> f) {
        List<R> result = new ArrayList<>();
        for (T s : list) {
            result.add(f.apply(s));
        }
        return result;
    }

    public static void main(String[] args) {
        try {
            String oneline = processFile((BufferedReader br) -> br.readLine());
            System.out.println("第一天数据：" + oneline);
            String twoline = processFile((BufferedReader br) -> br.readLine() + br.readLine());
            System.out.println("第二天数据：" + twoline);

            List<String> list = new ArrayList<>();
            list.add("fsg");
            list.add("");
            list.add("hfgh");
            list.add("hfjhggh");
            list.add("jghjryt");
            Predicate<String> nonEmptyStringPredicate = (String s) -> !s.isEmpty();
            List<String> nonEmpty = filter(list, nonEmptyStringPredicate);
            System.out.println(nonEmpty);

            forEach(Arrays.asList(1,2,3,4,5),(Integer i) -> System.out.println(i));

            List<Integer> l = map(Arrays.asList("lambdas", "in", "action"), (String s) -> s.length());
            System.out.println(l);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
